import React from 'react';
import { Card, Row, Col, Divider, Tooltip, Popconfirm, Tag, Alert, Empty, message } from 'antd';
import { history } from 'umi'
import { size } from 'lodash';
import moment from 'moment';
import { Icon } from '@/pages/Setting/Privilege/components/PrivilegeIcon';
import IconFont from '@/components/IconFont';
import { HighlightText } from '@/molecules';
import { useRequest } from '@/hooks';
import { deleteRoleInSubmitMode } from '@/pages/Setting/Privilege/services';
import { hasWorkFlowByType, gotoWorkFlowDetail } from '@/pages/WorkFlow/utils';
import authHelper from '@/utils/auth/helper';
import styles from './index.less';

const { checkCode } = authHelper;

// 模板列表组件
const TableList = ({ data, wrapStyles, query, fetchList }) => {
    // 删除模板
    const { run: deleteRun, fetches } = useRequest(param => deleteRoleInSubmitMode(param), {
        manual: true,
        fetchKey: code => code
    });

    const renderTag = (showStatus, showStatusName, auditCode) => {
        if (!!showStatusName && (showStatus === 1 || showStatus === -998 || showStatus === -999)) {
            return (
                <Tag
                    color={showStatus === 1 ? 'orange' : ''}
                    style={{ marginLeft: 12, cursor: showStatus === 1 ? 'pointer' : 'default' }}
                    onClick={e => {
                        if (showStatus === 1) {
                            e.stopPropagation();
                            history.push(gotoWorkFlowDetail(auditCode));
                        }
                    }}
                >
                    {showStatusName}
                </Tag>
            );
        }
        return null;
    };

    const renderContent = dataSource =>
        dataSource?.roles?.map(item => {
            const {
                code,
                icon,
                nameZh,
                remarkZh,
                advancedQuantity,
                functionalQuantity,
                basicQuantity,
                dutyQuantity,
                updateTime,
                showStatus,
                showStatusName,
                draftTime,
                auditCode
            } = item;
            return (
                <div className={styles.boxWrap} key={code}>
                    <Row
                        className={styles.templateRow}
                        style={{ cursor: checkCode('system:authorization:role:detail') ? 'pointer' : 'default' }}
                        onClick={() => {
                            if (checkCode('system:authorization:role:detail')) {
                                history.push({
                                    pathname: '/setting/privilege/templatemanagement/templateinfo',
                                    query: { code }
                                });
                            }
                        }}
                    >
                        <Col span={8} className={styles.templateName}>
                            <Icon disabled={showStatus === 1 || showStatus === -999} icon={icon} size={48} />
                            <ul>
                                <li>
                                    <HighlightText keywords={query?.keyword || ''}>{nameZh}</HighlightText>
                                    {renderTag(showStatus, showStatusName, auditCode)}
                                </li>
                                <li className={styles.smallGrayText}>
                                    <Tooltip
                                        placement="bottom"
                                        title={
                                            <div style={{ maxHeight: 350, overflow: 'auto', width: '100%' }}>
                                                {remarkZh}
                                            </div>
                                        }
                                        getPopupContainer={triggerNode => triggerNode.closest('ul')}
                                    >
                                        {remarkZh.substring(0, 300)}
                                    </Tooltip>
                                </li>
                            </ul>
                        </Col>
                        <Col span={5}>
                            <div>包含功能</div>
                            <div className={styles.smallGrayText}>
                                职能({functionalQuantity})
                                <Divider type="vertical" /> 高级({advancedQuantity}) <Divider type="vertical" /> 基础(
                                {basicQuantity})
                            </div>
                        </Col>
                        <Col span={4} style={{ padding: '0 24px' }}>
                            <div>授权岗位</div>
                            <div className={styles.smallGrayText}>{dutyQuantity}</div>
                        </Col>
                        <Col span={3}>
                            <div>更新时间</div>
                            <div className={styles.smallGrayText}>{moment(updateTime).format('YYYY/MM/DD HH:mm')}</div>
                        </Col>
                        <Col
                            span={4}
                            style={{ textAlign: 'right' }}
                            onClick={e => {
                                e.stopPropagation();
                            }}
                        >
                            <Tooltip title="编辑">
                                <IconFont
                                    disabled={showStatus === 1 || !checkCode('system:authorization:role:edit')}
                                    icon="iconlistfunction_edit_icon_default"
                                    isButton
                                    onClick={() => {
                                        history.push({
                                            pathname: '/setting/privilege/edittemplate',
                                            query: { code }
                                        });
                                    }}
                                />
                            </Tooltip>
                            <Divider type="vertical" />
                            <Tooltip title="复制">
                                <IconFont
                                    disabled={!checkCode('system:authorization:role:copy')}
                                    icon="iconcopy_o"
                                    isButton
                                    onClick={() => {
                                        history.push({
                                            pathname: '/setting/privilege/copytemplate',
                                            query: { code, actionType: 'copy' }
                                        });
                                    }}
                                />
                            </Tooltip>
                            <Divider type="vertical" />
                            <Popconfirm
                                title={`确定要删除${nameZh}？`}
                                arrowPointAtCenter
                                onConfirm={async () => {
                                    // 如果是草稿不走流程校验
                                    if (showStatus === -999) {
                                        const { code: resultCode, msg } = await deleteRun(code);
                                        if (resultCode === 10000) {
                                            message.success(msg);
                                            fetchList(query);
                                        } else {
                                            message.error(msg);
                                        }
                                    } else {
                                        // 校验流程是否存在
                                        const { workFlowUrl } = await hasWorkFlowByType('PrivilegeTemplateApply');
                                        if (workFlowUrl) {
                                            const { data: id, code: resultCode, msg } = await deleteRun(code);
                                            if (resultCode === 10000) {
                                                history.push(`${workFlowUrl}${id}`);
                                            } else {
                                                message.error(msg);
                                            }
                                        }
                                    }
                                }}
                                placement="topRight"
                                okText="确认"
                                cancelText="取消"
                                getPopupContainer={triggerNode => triggerNode.closest('.ant-card-body')}
                            >
                                <Tooltip title="删除">
                                    <IconFont
                                        disabled={
                                            showStatus === 1 ||
                                            fetches[code]?.loading ||
                                            !checkCode('system:authorization:role:delete')
                                        }
                                        icon="iconlistfunction_delete_icon_default"
                                        isButton
                                    />
                                </Tooltip>
                            </Popconfirm>
                        </Col>
                    </Row>
                    {showStatus === -998 && (
                        <Alert
                            message={`存在已保存未提交审批内容，上次编辑时间：${moment(draftTime).format(
                                'YYYY-MM-DD HH:mm'
                            )}`}
                            type="warning"
                            showIcon
                            closable
                            style={{ marginBottom: 20 }}
                        />
                    )}
                </div>
            );
        });

    return (
        <div style={{ ...wrapStyles }} className={styles.tableListWrap}>
            {data.map(item => {
                const len = size(item?.roles.filter(subItem => subItem.showStatus !== -999)); // 未提交的审批草稿不算数量

                return (
                    <Card
                        title={
                            <>
                                {item.roleTypeName} (<Tooltip title="不包含还未提交审批类型的模板">{len}</Tooltip>)
                            </>
                        }
                        className={styles.cardWrap}
                        key={item.roleType}
                    >
                        {size(item?.roles) > 0 ? renderContent(item) : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    </Card>
                );
            })}
        </div>
    );
};

export default TableList;
